package com.hexinfo.dmpro.admin.controller;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hexinfo.dmpro.common.annotation.AnonymousAccess;
import com.hexinfo.dmpro.common.annotation.Log;
import com.hexinfo.dmpro.common.base.BaseRequest;
import com.hexinfo.dmpro.common.base.BaseView;
import com.hexinfo.dmpro.common.base.Page;
import com.hexinfo.dmpro.common.exception.BadRequestException;
import com.hexinfo.dmpro.admin.model.Role;
import com.hexinfo.dmpro.admin.service.RoleService;
import com.hexinfo.dmpro.common.utils.ThrowableUtil;
import com.hexinfo.dmpro.script.config.model.RolesGit;
import com.hexinfo.dmpro.script.config.model.RolesPublishuser;
import com.hexinfo.dmpro.script.config.service.RolesGitService;
import com.hexinfo.dmpro.script.config.service.RolesPublishuserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * @ClassName RoleController
 * @Describe
 * @Author ml.wang
 * @Date 2021-06-17
 */
@Api(tags = "系统：角色管理")
@RestController
@RequestMapping("/api/roles")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RolesPublishuserService rolesPublishuserService;

    @Autowired
    private RolesGitService rolesGitService;

    @ApiOperation("返回全部的角色")
    @GetMapping(value = "/all")
    @PreAuthorize("@permission.check('roles:list','user:add','user:edit','platformManager', 'projectManager')")
    public ResponseEntity<Object> queryAll() {
        return new ResponseEntity<>(roleService.queryAll(new BaseRequest()), HttpStatus.OK);
    }

    @Log("查询角色")
    @ApiOperation("查询角色")
    @GetMapping
    @PreAuthorize("@permission.check('roles:list')")
    public ResponseEntity<Object> queryRoles(BaseView baseView, Page page) {
        return new ResponseEntity<>(roleService.queryRoles(BaseRequest.viewToRequest(baseView), page), HttpStatus.OK);
    }

    @ApiOperation("查询角色")
    @GetMapping(value = "/name/{name}")
    @AnonymousAccess
    public ResponseEntity<Object> nameRoles(@PathVariable String name) {
        return new ResponseEntity<>(roleService.findByName(name), HttpStatus.OK);
    }

    @ApiOperation("获取用户级别")
    @GetMapping(value = "/level")
    public ResponseEntity<Object> getLevel() {
        return new ResponseEntity<>(Dict.create().set("level", roleService.getLevels(null)), HttpStatus.OK);
    }

    @ApiOperation("获取单个role")
    @GetMapping(value = "/{id}")
    @PreAuthorize("@permission.check('roles:list')")
    public ResponseEntity<Object> getRoles(@PathVariable Long id) {
        return new ResponseEntity<>(roleService.findById(id), HttpStatus.OK);
    }

    @Log("新增角色")
    @ApiOperation("新增角色")
    @PostMapping
    @PreAuthorize("@permission.check('roles:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Role resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new role cannot already have an ID");
        }
        roleService.getLevels(resources.getLevel());
        roleService.save(resources);
        //添加到role-publishuser表中
        if(resources.getUsernameList().size() > 0){
            RolesPublishuser rolesPublishuser=new RolesPublishuser();
            for (String str :
                    resources.getUsernameList()) {
                rolesPublishuser.setRoleId(String.valueOf(resources.getId()));
                rolesPublishuser.setPublishuserUsername(str);
                rolesPublishuserService.save(rolesPublishuser);
            }
        }
        //添加到role-git表中
        if(resources.getGitIdList().size()>0){
            RolesGit rolesGit = new RolesGit();
            for (String str :
                    resources.getGitIdList()) {
                rolesGit.setRoleId(String.valueOf(resources.getId()));
                rolesGit.setGitId(str);
                rolesGitService.save(rolesGit);
            }
        }

        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("修改角色")
    @ApiOperation("修改角色")
    @PutMapping
    @PreAuthorize("@permission.check('roles:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Role resources) {
        roleService.getLevels(resources.getLevel());
        roleService.modify(resources);
        //修改role-publishuser表
        //先删除
        QueryWrapper<RolesPublishuser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ROLE_ID",resources.getId());
        rolesPublishuserService.remove(queryWrapper);
        //再添加
        if(resources.getUsernameList().size() > 0){
            RolesPublishuser rolesPublishuser=new RolesPublishuser();
            for (String str :
                    resources.getUsernameList()) {
                rolesPublishuser.setRoleId(String.valueOf(resources.getId()));
                rolesPublishuser.setPublishuserUsername(str);
                rolesPublishuserService.save(rolesPublishuser);
            }
        }
        //修改role-git表
        //先删除
        QueryWrapper<RolesGit> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ROLE_ID",resources.getId());
        rolesGitService.remove(queryWrapper2);
        //再添加
        if(resources.getGitIdList().size() > 0){
            RolesGit rolesGit=new RolesGit();
            for (String str :
                    resources.getGitIdList()) {
                rolesGit.setRoleId(String.valueOf(resources.getId()));
                rolesGit.setGitId(str);
                rolesGitService.save(rolesGit);
            }
        }
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除角色")
    @ApiOperation("删除角色")
    @DeleteMapping
    @PreAuthorize("@permission.check('roles:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) {
        for (Long id : ids) {
            Role role = roleService.findById(id);
            roleService.getLevels(role.getLevel());
        }
        try {
            roleService.delete(ids);
            rolesPublishuserService.removeByIds(ids);
            rolesGitService.removeByIds(ids);
        } catch (Throwable e) {
            ThrowableUtil.throwForeignKeyException(e, "所选角色存在用户关联，请取消关联后再试");
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("修改角色菜单")
    @ApiOperation("修改角色菜单")
    @PutMapping(value = "/menu")
    @PreAuthorize("@permission.check('roles:edit')")
    public ResponseEntity<Object> updateMenu(@RequestBody Role resources) {
        roleService.getLevels(resources.getLevel());
        roleService.updateMenu(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

}
